package com.iwinding.ladygg.net;

import android.content.Context;
import android.text.TextUtils;

import com.iwinding.ladygg.constant.SPConstant;
import com.iwinding.ladygg.net.request.AuthorizeReq;
import com.iwinding.ladygg.net.request.TokenReq;
import com.iwinding.ladygg.net.response.AccessTokenRp;
import com.iwinding.ladygg.net.response.AuthorizeRp;
import com.iwinding.ladygg.utils.GsonUtil;
import com.iwinding.ladygg.utils.LogUtil;
import com.iwinding.ladygg.utils.SPUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by 82218 on 2017/7/11.
 */

public class TokenInterceptor implements Interceptor {

    public static final String UNKNOWN_ACCESS_TOKEN = "1000";
    public static final String UNKNOWN_SESSION = "1030";
    public static final String UNKNOWN_USER_SESSION = "1031";

    private Context mContext;

    public TokenInterceptor(Context mContext) {
        this.mContext = mContext;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        if (isTokenExpired(response)) {//根据和服务端的约定判断token过期
            Request original = chain.request();
            LogUtil.print("静默自动刷新Token,然后重新请求数据");
            //同步请求方式，获取最新的Token
            String token = getNewToken();
            //使用新的Token，创建新的请求

            Request.Builder requestBuilder = chain.request()
                    .newBuilder()
                    .header("Cookie", "JSESSIONID=" + SPUtils.getSpPropertyString(mContext, SPConstant.COOKIE, ""));
            //请求体定制：统一添加token参数
            if (original.body() instanceof FormBody) {
                FormBody.Builder newFormBody = new FormBody.Builder();
                FormBody oidFormBody = (FormBody) original.body();
                for (int i = 0; i < oidFormBody.size(); i++) {
                    newFormBody.addEncoded(oidFormBody.encodedName(i), oidFormBody.encodedValue(i));
                }
                newFormBody.add("token", token);
                requestBuilder.method(original.method(), newFormBody.build());
            }
            Request nweRequest = requestBuilder.build();
            //重新请求
            return chain.proceed(nweRequest);
        }
        return chain.proceed(request);
    }

    /**
     * 根据Response，判断Token是否失效
     *
     * @param response
     * @return
     */
    private boolean isTokenExpired(Response response) throws IOException {
        boolean isExpired = false;
        if (response.code() == 200) {
            String json = response.body().string();
            LogUtil.i("@hzy", "isTokenExpired json---------" + json);
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(json);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            if (jsonObject != null) {
                String errcode = jsonObject.optString("errCode");
                if (!TextUtils.isEmpty(errcode)) {
                    switch (errcode) {
                        case UNKNOWN_ACCESS_TOKEN:
                        case UNKNOWN_SESSION:
                        case UNKNOWN_USER_SESSION:
                            isExpired = true;
                            SPUtils.putSpProperty(mContext,SPConstant.IS_TOKEN_EXPIRED,true);
                            break;
                    }
                }
            }
            LogUtil.i("@hzy", "isTokenExpired-0--------" + isExpired);
        }
        return isExpired;
    }

    /**
     * 同步请求方式，获取最新的Token
     *
     * @return
     */
    private String getNewToken() throws IOException {
        // 通过一个特定的接口获取新的token，此处要用到同步的retrofit请求
        ResponseBody authResponseBody = RequestManager.postAuthorize(new AuthorizeReq());
        AuthorizeRp authorize =
                GsonUtil.getInstance().formJson(authResponseBody.string().toString(), AuthorizeRp.class);
        ResponseBody tokenResponseBody = RequestManager.postAccessToken(new TokenReq(authorize.code));
        String jsonStr = tokenResponseBody.string();
        LogUtil.i("@hzy", "icane----Token:" + jsonStr);
        AccessTokenRp accessTokenRp =
                GsonUtil.getInstance().formJson(jsonStr, AccessTokenRp.class);
        String access_token = accessTokenRp.access_token;
        return access_token;
    }

}
